import {
    createRouter,
    createWebHistory
} from "vue-router";
import {
    useUserStore
} from "../store/userStore";
import {
    showToast
} from "vant";

const router = createRouter({
    history: createWebHistory(),
    routes: [{
            path: '/login',
            component: () => import('../views/Login.vue')
        },
        {
            path: '/product/:id',
            name: 'ProductDetail', // 添加 name 属性
            component: () => import('../views/ProductDetailView.vue')
        },
        {
            path: '/register',
            component: () => import('../views/Register.vue')
        },
        {
            path: '/pay',
            component: () => import('../views/PayView.vue')
        },
        {
            path: '/browsing-history',
            component: () => import('../views/BrowsingHistoryView.vue')
        },
        {
            path: '/settings',
            component: () => import('../views/SettingsView.vue')
        },
        {
            path: '/',
            component: () => import('../views/Layout.vue'),
            children: [{
                path: '',
                component: () => import('../views/HomeView.vue')
            }, {
                path: 'category',
                component: () => import('../views/CategoryView.vue')
            }, {
                path: 'cart',
                component: () => import('../views/CartView.vue')
            }, {
                path: 'profile',
                component: () => import('../views/ProfileView.vue')
            }, {
                path: 'publish',
                component: () => import('../views/PublishView.vue')
            }, ]
        },
        {
            path: '/:pathMatch(.*)*',
            component: () => import('../views/NotFoundView.vue')
        }
    ]
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
    // 去首页
    if (to.path === '/') {
        // token 存在
        if (useUserStore().user.token) {
            // 放行
            next()
        } else {
            // 不存在 跳转登录
            next('/login')
        }
        // 去登录或注册
    } else if (to.path === '/register' || to.path === '/login') {
        // token 存在
        if (useUserStore().user.token) {
            next('/')
            showToast('请先退出登录')
        } else {
            // 不存在
            next()
        }
    } else {
        // 放行
        next()
    }
})


export default router